package com.example.springbootServiceNetwork.demos.web.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.springbootServiceNetwork.demos.web.Config.AlipayConfig;
import com.example.springbootServiceNetwork.demos.web.Dao.AlipayLogDao;
import com.example.springbootServiceNetwork.demos.web.Dao.OrderDao;
import com.example.springbootServiceNetwork.demos.web.Dto.AliPay;
import com.example.springbootServiceNetwork.demos.web.Dto.AliReturnPay;
import com.example.springbootServiceNetwork.demos.web.Entity.AlipayLog;
import com.example.springbootServiceNetwork.demos.web.Entity.Order;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@RestController
@RequestMapping("/alipay")
public class AlipayController {
    @Resource
    private AlipayConfig alipayConfig;
    @Resource
    private AlipayLogDao alipayLogDao;
    @Resource
    private OrderDao orderDao;

    /**
     * 请求支付宝支付
     * 返货from表单
     */
    @GetMapping("/pay")
    public void pay(AliPay aliPay, HttpServletResponse response) {
        try {
          Order order = new Order();
          order.setOrderId(aliPay.getOutTradeNo());
          order =orderDao.selectById(order);
          if (!(order==null)){
              //1.创建client，通过阿里SDK提供的client，负责调用支付宝的API
              AlipayClient alipayClient = new DefaultAlipayClient(
                      alipayConfig.getServerUrl(),
                      alipayConfig.getAppId(),
                      alipayConfig.getAppPrivateKey(),
                      alipayConfig.getFormat(),
                      alipayConfig.getCharset(),
                      alipayConfig.getAlipayPublicKey(),
                      alipayConfig.getSignType()
              );
              /* 2.创建request，并设置request参数 */
              AlipayTradePagePayRequest request = getAlipayTradePagePayRequest(aliPay, order);
              //执行请求，拿到响应的结果，返回给浏览器
              String form  = alipayClient.pageExecute(request).getBody();
              //设置响应结果，将返回的内容写出到浏览器
              response.setContentType("text/html;charset=" + alipayConfig.getCharset());
              response.getWriter().write(form);//直接将完整的表单html输出到页面
              response.getWriter().flush();
              response.getWriter().close();
          }



        } catch (Exception e) {
//            e.printStackTrace();
            e.fillInStackTrace();
        }
    }

    @NotNull
    private AlipayTradePagePayRequest getAlipayTradePagePayRequest(AliPay aliPay, Order order) {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl());//设置异步地址
        //支付时候前端把地址传过来
        request.setReturnUrl(aliPay.getBackUrl());
        JSONObject jsonObject = new JSONObject();
        //商户订单号
        jsonObject.put("out_trade_no", order.getOrderId());
        //商品价格
        jsonObject.put("total_amount", order.getPaidPrice());
        //商品标题
        jsonObject.put("subject", order.getOrderName());
        //产品编码
        jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(jsonObject.toString());
        return request;
    }

    /**
     *二维码支付
     * 返回二维码
     */
    @PostMapping("/sandPay")
    public String sandboxPay(AliPay aliPay) {
        try {
            Order order = new Order();
            order.setOrderId(aliPay.getOutTradeNo());
            order =orderDao.selectById(order);
            if (!(order==null)){
                //1.创建client，通过阿里SDK提供的client，负责调用支付宝的API
                AlipayClient alipayClient = new DefaultAlipayClient(
                        alipayConfig.getServerUrl(),
                        alipayConfig.getAppId(),
                        alipayConfig.getAppPrivateKey(),
                        alipayConfig.getFormat(),
                        alipayConfig.getCharset(),
                        alipayConfig.getAlipayPublicKey(),
                        alipayConfig.getSignType()
                );
                AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
                alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("out_trade_no", order.getOrderId());// 商户订单号
                jsonObject.put("total_amount", aliPay.getTotalAmount());// 商品价格
                jsonObject.put("subject", aliPay.getSubject());// 商品标题
                jsonObject.put("store_id", aliPay.getStoreName());//组织或公司名
//            jsonObject.put("timeout_express","5m");// 订单有效时间
                alipayRequest.setBizContent(jsonObject.toString());
                AlipayTradePrecreateResponse response = alipayClient.execute(alipayRequest);
                System.out.println("创建订单结果:" + response.getBody());
                System.out.println("订单编号是" + response.getOutTradeNo());
                //            AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
                return response.getQrCode();
            }else {
                return "订单错误";
            }

        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 支付宝回调
     */
    @PostMapping("/notify")
    public void call( HttpServletResponse response, AliReturnPay aliReturnPay) {
        response.setContentType("type=text/html;charset=UTF-8");
        AlipayLog alipayLog = JSON.parseObject(JSON.toJSONString(aliReturnPay), AlipayLog.class);
        //插入日志操作
        alipayLogDao.insert(alipayLog);
        //更新订单信息
        Order order =new Order();
        //支付流水号
        order.setAlipayTraceNo(aliReturnPay.getTrade_no());
        //更新时间
        order.setPayTime(new Date());
        //已支付状态
        order.setPayStatus("Y");
        order.setPayStatusName("已支付");
        //更新订单状态
        order.setOrderStatus("Y");
        order.setOrderStatusName("已支付");
        orderDao.updateById(order);
    }

    /**
     *查询支付宝支付的订单
     */
    @PostMapping("/order")
    public String selectArder(AliPay aliPay){
        try {
            Order order = new Order();
            order.setOrderId(aliPay.getOutTradeNo());
            order =orderDao.selectById(order);
            if (!(order==null)){
                //1.创建client，通过阿里SDK提供的client，负责调用支付宝的API
                AlipayClient alipayClient = new DefaultAlipayClient(
                        alipayConfig.getServerUrl(),
                        alipayConfig.getAppId(),
                        alipayConfig.getAppPrivateKey(),
                        alipayConfig.getFormat(),
                        alipayConfig.getCharset(),
                        alipayConfig.getAlipayPublicKey(),
                        alipayConfig.getSignType()
                );
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("out_trade_no",order.getOrderId());// 商户订单号
                jsonObject.put("trade_no",order.getAlipayTraceNo());//支付宝订单编号
                jsonObject.put("query_options",aliPay.getQueryOptions());//指定需要返回那些信息
                request.setBizContent(jsonObject.toString());
                AlipayTradeQueryResponse response = alipayClient.execute(request);
                if(response.isSuccess()){
                    System.out.println("调用成功");
                    System.out.println(response.getBody());
                }else {
                    response.getBody();
                    System.out.println("调用失败");
                }
            }

        }catch (Exception e){
//            e.printStackTrace();
            e.fillInStackTrace();
        }
        return null;
    }

    /**
     * 全额退款
     */
    @PostMapping("/refundAll")
    public String refundAll(@RequestBody AliPay aliPay) {
        try {
            //1.创建client，通过阿里SDK提供的client，负责调用支付宝的API
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getServerUrl(),
                    alipayConfig.getAppId(),
                    alipayConfig.getAppPrivateKey(),
                    alipayConfig.getFormat(),
                    alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getSignType()
            );
            //2.创建request，并设置request参数
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("out_trade_no",aliPay.getOutTradeNo());// 商户订单号
            jsonObject.put("trade_no",aliPay.getAlipayTraceNo());//支付宝交易号
            jsonObject.put("refund_amount",aliPay.getRefundAmount());//退款金额
            jsonObject.put("refund_reason",aliPay.getRefundReason());//退款原因
            request.setBizContent(jsonObject.toString());
            //执行请求，拿到响应的结果，返回给浏览器
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            System.out.println(response.getBody());
            if (response.isSuccess()) {
                System.out.println(response.getBody());
                return "退款成功";
            } else {
                return "退款失败";
            }
        } catch (Exception e) {
//            e.printStackTrace();
            e.fillInStackTrace();
            return "退款异常";
        }
    }

    /**
     * 部分退款
     */
    @PostMapping("/refund")
    public String refund(@RequestBody AliPay aliPay) {
        try {
            //1.创建client，通过阿里SDK提供的client，负责调用支付宝的API
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getServerUrl(),
                    alipayConfig.getAppId(),
                    alipayConfig.getAppPrivateKey(),
                    alipayConfig.getFormat(),
                    alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getSignType()
            );
            //2.创建request，并设置request参数
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("out_trade_no",aliPay.getOutTradeNo());// 商户订单号
            jsonObject.put("trade_no",aliPay.getAlipayTraceNo());//支付宝交易号
            jsonObject.put("refund_amount",aliPay.getRefundAmount());//退款金额
            jsonObject.put("refund_reason",aliPay.getRefundReason());//退款原因
            jsonObject.put("out_request_no","HZ01RF001");//部分退款
            request.setBizContent(jsonObject.toString());
            //执行请求，拿到响应的结果，返回给浏览器
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                System.out.println(response.getBody());
                return "退款成功";
            } else {
                return "退款失败";
            }
        } catch (Exception e) {
//            e.printStackTrace();
            e.fillInStackTrace();
            return "退款异常";
        }
    }


}
